#include "stdafx.h"
#include "EyeTracker.h"


EyeTracker::EyeTracker(void)
{
	ip_address = "127.0.0.1";
	port = PORT;
	socket_type = DEFAULT_PROTO;
	delimiters = " ";
}


EyeTracker::~EyeTracker(void)
{
}

int EyeTracker::init()
{

	// Request Winsock version 2.2
    if ((retval = WSAStartup(0x202, &wsaData)) != 0)
    {
        fprintf(stderr,"Server: WSAStartup() failed with error %d\n", retval);
        WSACleanup();
        return -1;
    }
    
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = inet_addr(ip_address);
 
    /* Port MUST be in Network Byte Order */
    local.sin_port = htons(port);
    // UDP socket
    listen_socket = socket(AF_INET, socket_type,0);
 
    if (listen_socket == INVALID_SOCKET){
        fprintf(stderr,"Server: socket() failed with error %d\n", WSAGetLastError());
        WSACleanup();
        return -1;
    }
    
	if (bind(listen_socket, (struct sockaddr*)&local, sizeof(local)) == SOCKET_ERROR)
    {
		fprintf(stderr,"Server: bind() failed with error %d\n", WSAGetLastError());
		WSACleanup();
		return -1;
	}

	return 0;
}

EyeTracker::return_struct EyeTracker::get_coordinate()
{

	fromlen =sizeof(from);
    msgsock = listen_socket;
 
    retval = recvfrom(msgsock,Buffer, sizeof(Buffer), 0, (struct sockaddr *)&from, &fromlen);
    //printf("Server: Received datagram from %s\n", inet_ntoa(from.sin_addr
	std::string ret_str(Buffer);
	ret_str = ret_str.substr(0, retval);
	//std::cout << ret_str << std::endl;
        
		
	size_t current;
	size_t next = -1;
		
	//skip first two data catagories
	current = next + 1;
	next = ret_str.find_first_of( delimiters, current );
	current = next + 1;
	next = ret_str.find_first_of( delimiters, current );
		
	//get x
	current = next + 1;
	next = ret_str.find_first_of( delimiters, current );
	std::string x = ret_str.substr( current, next - current );
		
	//get y
	current = next + 1;
	next = ret_str.find_first_of( delimiters, current );
	std::string y = ret_str.substr( current, next - current );

	//std::cout << "x: " << x << " y: " << y << std::endl;
	std::istringstream i(x);
	std::istringstream j(y);

	struct return_struct result;
	result.ret_val = retval;
	i >> result.x;
	j >> result.y;
    
	return result;
}